package com.gzz.controller;


import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gzz.common.R;
import com.gzz.common.StringIntersection;
import com.gzz.pojo.Activity;
import com.gzz.pojo.Food;
import com.gzz.pojo.Scenery;
import com.gzz.service.FoodService;
import com.gzz.service.ImgsRespService;
import com.gzz.service.OssUploadService;
import com.gzz.vo.FoodList;
import com.gzz.vo.FoodVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

import static com.gzz.utils.OssUtils.*;

/**
 * <p>
 *  前端控制器，美食信息控制
 * </p>
 *
 */

@RestController
@RequestMapping("/api/food")
public class FoodController {

    @Autowired
    private FoodService foodService;

    @Autowired
    OssUploadService ossUploadService;
    @Autowired
    ImgsRespService imgsRespService;



    @GetMapping("/list")
    public R<List<Food>> getAll(@RequestParam(name = "value") Integer value,@RequestParam(name = "curPage")Integer curPage,@RequestParam(name="pageSize") Integer pageSize)
    {
        return R.success(getListR(value, curPage, pageSize));
    }
    // 根据前端传入的value进行相应的排序，并且手动分页返回给前端
    private List<Food> getListR(@RequestParam(name = "value") Integer value, @RequestParam(name = "curPage") Integer curPage, @RequestParam(name = "pageSize") Integer pageSize) {
        // 转字符串好比较
        String searchValue = value.toString();
        // 调用mybatisplus的list方法，获取美食信息列表
        List<Food> foodList = foodService.list();
        // 根据前端传的value判断排序规则
        if(searchValue.equals("0"))
        {
            // 根据距离升序排序
            foodList.sort(new Comparator<Food>() {
                @Override
                public int compare(Food o1, Food o2) {
                    return o1.getDistant().doubleValue()-o2.getDistant().doubleValue()>0?1:-1;
                }
            });
        }
        else if(searchValue.equals("1"))
        {
            // 根据访问量倒序排序
            foodList.sort(new Comparator<Food>() {
                @Override
                public int compare(Food o1, Food o2) {
                    return o1.getVisits()-o2.getVisits()<0?1:-1;
                }
            });
        } else if(searchValue.equals("2"))
        {
            // 根据分数倒序排序
                foodList.sort(new Comparator<Food>() {
                    @Override
                    public int compare(Food o1, Food o2) {
                       return o1.getScore()- o2.getScore()<0?1:-1;
                    }
                });
        }
        // 手动分页返回给前端数据
        Integer num = foodList.size();
        Integer end = (curPage)*pageSize;
        if(num<(curPage)*pageSize){
            end = num;
        }
        // 截取美食列表
        foodList.subList((curPage-1)*pageSize,end);
        for (Food food : foodList) {
            // 设置此次数据的总量
            food.setTotNum(num);
        }
        return foodList;
    }
    // 根据美食名称进行模糊查询，用户端调用
    @GetMapping("/find")
    public R<List<Food>> getResult(@RequestParam(name = "value") Integer value,@RequestParam(name = "curPage")Integer curPage,@RequestParam(name="pageSize") Integer pageSize,@RequestParam(name="searchValue") String findValue)
    {
        // mybatisplus查询器
        LambdaQueryWrapper<Food> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(Food::getFoodName,findValue);
        List<Food> list = foodService.list(lambdaQueryWrapper);
        return R.success(list);

    }
    // 根据美食id查询美食详情数据，返回给前端
    @GetMapping("/detail")
    public R<FoodVo> getDetail(@RequestParam(name = "foodId") Long foodId)
    {
        // 根据美食id获取美食详情信息
        return R.success(foodService.getFoodVobyId(foodId));
    }
    // 管理端根据美食名称进行模糊查询，美食标签做模糊查询
    @GetMapping("/findlist")
    public R<FoodList> getFindList(@RequestParam(name = "pageNum")Integer pageNum,@RequestParam(name = "pageSize")Integer pageSize,@RequestParam(name="searchFood") String searchFood,@RequestParam(name = "searchTips") String searchTips)
    {
        // mybatisplus提供的条件查询器
        QueryWrapper<Food> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(searchFood!="","food_Name",searchFood);
        queryWrapper.like(searchTips!="","food_Tips",searchTips);
        // mybatisplus提供的分页查询
        Page<Food> foodPage = new Page<>(pageNum,pageSize);
        List<Food> foodList = foodService.getFindList(foodPage,queryWrapper);

        List<FoodVo> foodVoList = foodService.getImage(foodList);
        // 将foodVoList转换为FoodList，带有数据总量信息，提供给前端。
        FoodList foodList1 = new FoodList(foodVoList,foodService.list().size());
        return R.success(foodList1);
    }

    // 更新food信息，唯一的不同是不需要再生成id,而且需要先删除该food对应图片表的图片，再添加更新的图片
    @PutMapping("/update")
    public R<String> updateFood(@RequestBody FoodVo foodVo)
    {

        Food food = new Food();
        // 对象属性复制
        BeanUtils.copyProperties(foodVo,food);
        // 调用mybatisplus方法 保存或更新数据
        foodService.saveOrUpdate(food);

        // 获取图片列表
        List<String> imgs = foodVo.getImgs();

        Integer typeId = FoodType;
        Long id = foodVo.getFoodId();
        // 先删除
        imgsRespService.removeByIdAndTypeId(id,typeId);
        // 保存图片列表到数据库的图片表并返回是否成功
        boolean r = imgsRespService.saveList(imgs,id,typeId);

        if(!r){
            return R.error("数据异常");
        }

        return R.success("success");

    }


    // post请求添加新的food信息，从请求体中获取需要保存的FoodVo数据。
    @PostMapping("/add")
    public  R<String> addDetail(HttpServletRequest httpServletRequest, @RequestBody FoodVo foodVo){

        Food food = new Food();
        BeanUtils.copyProperties(foodVo,food);
        // 生成id
        Long id = (long)Math.abs(UUID.randomUUID().hashCode());
        // 设置id
        food.setFoodId(id);
        // 通过mybatisplus提供的save方法保存food数据到数据库对应的food表
        foodService.save(food);

        // 获取图片列表
        List<String> imgs = foodVo.getImgs();

        Integer typeId = GoodTypeId;
        // 通过foodid，类型id可以确认唯一的图片
        //r存储的是判断是否成功保存
        boolean r = imgsRespService.saveList(imgs, foodVo.getFoodId(),typeId);
        if(!r){
            return R.error("数据异常");
        }
        return R.success("success");
    }


    // 按照美食id在数据库中删美食信息
    @DeleteMapping("/delete")
    public R deleteFood(@RequestParam(name = "foodId") Long foodId)
    {
        //mybatisplus提供的条件查询
        QueryWrapper<Food> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("food_Id",foodId);
        foodService.remove(queryWrapper);
        return R.success(true);
    }
    // 图片上传处理
    @PostMapping("/upload")
    public R<String> Scupload(String type,@RequestParam("file") MultipartFile multipartFile){
        // 利用阿里云对象存储服务存储图片文件，并且返回图片路径给前端。
        String imgUrl = ossUploadService.uploadFile(multipartFile,type);

        if(imgUrl!="error"){
            return R.success(imgUrl);
        }
        return R.error(imgUrl);
    }
}


